﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Speech.Recognition;
using System.Text;
using System.Windows.Forms;

namespace AdvancedSpeech
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (textBoxNewElement.Text != string.Empty)
            {
                listBoxGrammar.Items.Add(textBoxNewElement.Text);
                textBoxNewElement.Text = "";
                textBoxNewElement.Focus();
            }
        }


        private void initRecognition() 
        {
            SpeechRecognizer recognizer = new System.Speech.Recognition.SpeechRecognizer();
            recognizer.LoadGrammar(prepareGrammar());
        }

        private Grammar prepareGrammar()
        {
            GrammarBuilder builder = new GrammarBuilder();
            Choices choices = new Choices();
            foreach (string item in listBoxGrammar.Items)
	        {
                choices.Add(item);
	        }
            builder.Append(choices);
            Grammar grammar = new Grammar(builder);
            grammar.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(grammar_SpeechRecognized);
            return grammar;
        }

        private void grammar_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            for (int i = 0; i < listBoxGrammar.Items.Count; i++)
            {
                if ((string)listBoxGrammar.Items[i] == e.Result.Text)
                {
                    listBoxGrammar.SelectedIndex = i;
                }
            }
        }

        private void buttonInit_Click(object sender, EventArgs e)
        {
            initRecognition();
        }
    }
}
